/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.images;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Random;

/**
 * <p>Project: jse2204 - WaterText
 * <p>Powered by webrx On 2022-09-27 08:41:54
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class WaterText {
    public static void main(String[] args) {
        waters(new File("D:\\abc"));

    }

    public static void waters(File dir) {
        for (File f : dir.listFiles()) {
            if (f.isDirectory()) {
                waters(f);
            }

            if (f.isFile() && f.getName().endsWith(".jpg") || f.getName().endsWith(".png")) {
                water(f, "13014577033");
            }
        }

        if (dir.isFile() && dir.getName().endsWith(".jpg") || dir.getName().endsWith(".png")) {
            water(dir, "13014577033");
        }
    }

    public static void water(File file, String text) {
        String f = file.getName();
        String t = f.substring(f.lastIndexOf(".") + 1).toLowerCase();
        try {
            BufferedImage i = ImageIO.read(file);
            int width = i.getWidth();
            int height = i.getHeight();
            if (width < 200 || height < 50) return;
            Graphics2D g = i.createGraphics();
            //设置线条和文件的，抗锯齿（平滑）
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);

            Font font = Font.createFont(Font.TRUETYPE_FONT, new File("fonts/FZCCHJW.TTF"));
            font = font.deriveFont(Font.PLAIN, 35);
            g.setFont(font);
            FontMetrics fm = g.getFontMetrics();
            int fw = fm.stringWidth(text);
            int fh = fm.getAscent() - (fm.getHeight() - fm.getAscent());

            //正中央
            int x = (width - fw) / 2;
            int y = (height - fh) / 2 + fh;

            //随机深色 透明度 88
            Random rand = new Random();
            Color color = new Color(rand.nextInt(30) + 50, rand.nextInt(30) + 50, rand.nextInt(30) + 50, 100);
            g.setColor(color);

            g.drawString(text, x, y);
            ImageIO.write(i, t, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
